<template>
  <admin-layout>
    <div class="statistics-view" v-loading="isOverallLoading">
      <h2 class="page-title">统计分析</h2>

      <!-- 网络错误提示 -->
      <el-alert
        v-if="networkError"
        title="网络连接失败"
        type="error"
        description="无法连接到服务器获取统计数据，请检查您的网络连接并重试。"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      >
        <template #default>
          <div class="network-error-actions">
            <el-button type="primary" size="small" @click="retryFetchData">
              重新加载
            </el-button>
          </div>
        </template>
      </el-alert>

      <!-- 时间范围选择 -->
      <el-card class="filter-card">
        <div class="filter-container">
          <el-radio-group
            v-model="timeRange"
            @change="handleTimeRangeChange"
            :disabled="isOverallLoading"
          >
            <el-radio-button label="week">近7天</el-radio-button>
            <el-radio-button label="month">近30天</el-radio-button>
            <el-radio-button label="quarter">近90天</el-radio-button>
            <el-radio-button label="year">近一年</el-radio-button>
          </el-radio-group>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            :disabled="isOverallLoading"
          />
        </div>
      </el-card>

      <!-- 内容区域 -->
      <div>
        <!-- 用户增长统计 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长统计</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading.users">
            <div ref="userGrowthChart" class="chart"></div>
          </div>
        </el-card>

        <!-- 订单统计 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单统计</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading.orders">
            <div ref="orderStatsChart" class="chart"></div>
          </div>
        </el-card>

        <!-- 商家分布 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>商家分类分布</span>
                </div>
              </template>
              <div class="chart-container" v-loading="loading.merchants">
                <div ref="merchantCategoryChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>商品分类分布</span>
                </div>
              </template>
              <div class="chart-container" v-loading="loading.products">
                <div ref="productCategoryChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 骑手统计 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>骑手配送统计</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading.riders">
            <div ref="riderStatsChart" class="chart"></div>
          </div>
        </el-card>

        <!-- 热门商品排行 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>热门商品排行</span>
            </div>
          </template>
          <div class="table-container" v-loading="loading.hotProducts">
            <el-table :data="hotProducts" style="width: 100%" stripe>
              <el-table-column type="index" label="排名" width="80" />
              <el-table-column prop="name" label="商品名称" min-width="120" />
              <el-table-column
                prop="storeName"
                label="所属店铺"
                min-width="120"
              />
              <el-table-column prop="sales" label="销量" width="100" sortable />
            </el-table>
          </div>
        </el-card>
      </div>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import AdminLayout from "@/components/admin/AdminLayout.vue";
import { getPlatformStats } from "@/api";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { LineChart, BarChart, PieChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer,
]);

// 图表引用
const userGrowthChart = ref<HTMLElement | null>(null);
const orderStatsChart = ref<HTMLElement | null>(null);
const merchantCategoryChart = ref<HTMLElement | null>(null);
const productCategoryChart = ref<HTMLElement | null>(null);
const riderStatsChart = ref<HTMLElement | null>(null);

// 图表实例
let userGrowthChartInstance: echarts.ECharts | null = null;
let orderStatsChartInstance: echarts.ECharts | null = null;
let merchantCategoryChartInstance: echarts.ECharts | null = null;
let productCategoryChartInstance: echarts.ECharts | null = null;
let riderStatsChartInstance: echarts.ECharts | null = null;

// 时间范围
const timeRange = ref("month");
const dateRange = ref<string[]>([]);

// 加载状态
const loading = reactive({
  users: false,
  orders: false,
  merchants: false,
  products: false,
  hotProducts: false,
  riders: false,
});

// 网络错误状态
const networkError = ref(false);

// 热门商品数据
const hotProducts = ref([]);

// 整体加载指示器
const isOverallLoading = ref(false);

// 处理时间范围变化
const handleTimeRangeChange = (value: string) => {
  const now = new Date();
  const end = formatDate(now);
  let start: string;

  switch (value) {
    case "week":
      start = formatDate(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000));
      break;
    case "month":
      start = formatDate(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000));
      break;
    case "quarter":
      start = formatDate(new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000));
      break;
    case "year":
      start = formatDate(new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000));
      break;
    default:
      start = formatDate(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000));
  }

  dateRange.value = [start, end];
  fetchAllData();
};

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    timeRange.value = "custom";
    fetchAllData();
  }
};

// 格式化日期
const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 获取所有数据
const fetchAllData = async () => {
  isOverallLoading.value = true;
  networkError.value = false; // 重置网络错误状态

  try {
    // 构建API参数
    const params: { startDate?: string; endDate?: string } = {};
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }

    // 只调用一次API获取所有数据
    const res = await getPlatformStats(params);
    let data: any = null;
    if (res.data && res.data.data) {
      data = res.data.data;
    } else if (res.data) {
      data = res.data;
    }

    console.log("统计数据:", data);

    if (data) {
      // 设置所有加载状态为true
      Object.keys(loading).forEach((key) => {
        loading[key] = true;
      });

      try {
        // 处理用户增长数据
        if (data.newUsersData && typeof data.newUsersData === "object") {
          const dates = Object.keys(data.newUsersData).sort();
          const userCounts = dates.map((date) => data.newUsersData[date]);
          renderUserGrowthChart({ dates, userCounts });
        } else {
          renderUserGrowthChart({ dates: [], userCounts: [] });
        }
      } catch (error) {
        console.error("处理用户增长数据失败:", error);
        renderUserGrowthChart({ dates: [], userCounts: [] });
      } finally {
        loading.users = false;
      }

      try {
        // 处理订单统计数据
        if (data.orderCountData && data.orderAmountData) {
          const dates = Object.keys(data.orderCountData).sort();
          const orderCount = dates.map((date) => data.orderCountData[date]);
          const orderAmount = dates.map((date) => data.orderAmountData[date]);
          renderOrderStatsChart({ dates, orderCount, orderAmount });
        } else {
          renderOrderStatsChart({ dates: [], orderCount: [], orderAmount: [] });
        }
      } catch (error) {
        console.error("处理订单统计数据失败:", error);
        renderOrderStatsChart({ dates: [], orderCount: [], orderAmount: [] });
      } finally {
        loading.orders = false;
      }

      try {
        // 处理商家分类数据
        if (data.topStores && Array.isArray(data.topStores)) {
          const merchantData = data.topStores.map((item: any) => ({
            value: item.orderCount || 0,
            name: item.storeName,
          }));
          renderMerchantCategoryChart(merchantData);
        } else {
          renderMerchantCategoryChart([]);
        }
      } catch (error) {
        console.error("处理商家分类数据失败:", error);
        renderMerchantCategoryChart([]);
      } finally {
        loading.merchants = false;
      }

      try {
        // 处理商品分类数据
        if (data.topFoods && Array.isArray(data.topFoods)) {
          const productData = data.topFoods.map((item: any) => ({
            value: item.salesCount || 0,
            name: item.foodName,
          }));
          renderProductCategoryChart(productData);
        } else {
          renderProductCategoryChart([]);
        }
      } catch (error) {
        console.error("处理商品分类数据失败:", error);
        renderProductCategoryChart([]);
      } finally {
        loading.products = false;
      }

      try {
        // 处理热门商品数据
        if (data.topFoods && Array.isArray(data.topFoods)) {
          hotProducts.value = data.topFoods.map((item: any) => ({
            name: item.foodName,
            storeName: item.storeName,
            sales: item.salesCount || 0,
          }));
        } else {
          hotProducts.value = [];
        }
      } catch (error) {
        console.error("处理热门商品数据失败:", error);
        hotProducts.value = [];
      } finally {
        loading.hotProducts = false;
      }

      try {
        // 处理骑手统计数据 (可能没有此数据)
        // 使用空数据结构
        const emptyData = {
          dates: [] as string[],
          riderCount: [] as number[],
          deliveryCount: [] as number[],
        };
        renderRiderStatsChart(emptyData);
      } catch (error) {
        console.error("处理骑手统计数据失败:", error);
        renderRiderStatsChart({
          dates: [],
          riderCount: [],
          deliveryCount: [],
        });
      } finally {
        loading.riders = false;
      }
    } else {
      // 如果没有数据，则渲染空图表
      renderUserGrowthChart({ dates: [], userCounts: [] });
      renderOrderStatsChart({ dates: [], orderCount: [], orderAmount: [] });
      renderMerchantCategoryChart([]);
      renderProductCategoryChart([]);
      hotProducts.value = [];
      renderRiderStatsChart({
        dates: [],
        riderCount: [],
        deliveryCount: [],
      });

      // 重置所有加载状态
      Object.keys(loading).forEach((key) => {
        loading[key] = false;
      });
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);

    // 检查是否是网络错误
    if (error && (error as Error).message === "网络连接失败") {
      networkError.value = true;
    }

    ElMessage.error("获取统计数据失败，请稍后重试");

    // 渲染空图表
    renderUserGrowthChart({ dates: [], userCounts: [] });
    renderOrderStatsChart({ dates: [], orderCount: [], orderAmount: [] });
    renderMerchantCategoryChart([]);
    renderProductCategoryChart([]);
    hotProducts.value = [];
    renderRiderStatsChart({
      dates: [],
      riderCount: [],
      deliveryCount: [],
    });

    // 重置所有加载状态
    Object.keys(loading).forEach((key) => {
      loading[key] = false;
    });
  } finally {
    isOverallLoading.value = false;
  }
};

// 重试加载数据
const retryFetchData = () => {
  fetchAllData();
};

// 渲染用户增长图表
const renderUserGrowthChart = (data: {
  dates: string[];
  userCounts: number[];
}) => {
  if (!userGrowthChart.value) return;

  if (!userGrowthChartInstance) {
    userGrowthChartInstance = echarts.init(userGrowthChart.value);
  }

  const option = {
    title: {
      text: "用户增长趋势",
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["新增用户"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "新增用户",
        type: "line",
        data: data.userCounts,
        smooth: true,
        lineStyle: {
          color: "#1976d2",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(25, 118, 210, 0.5)",
              },
              {
                offset: 1,
                color: "rgba(25, 118, 210, 0.1)",
              },
            ],
          },
        },
      },
    ],
  };

  userGrowthChartInstance.setOption(option);
};

// 渲染订单统计图表
const renderOrderStatsChart = (data: {
  dates: string[];
  orderCount: number[];
  orderAmount: number[];
}) => {
  if (!orderStatsChart.value) return;

  if (!orderStatsChartInstance) {
    orderStatsChartInstance = echarts.init(orderStatsChart.value);
  }

  const option = {
    title: {
      text: "订单统计",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: ["订单数量", "订单金额"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: data.dates,
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "订单数量",
        position: "left",
      },
      {
        type: "value",
        name: "订单金额",
        position: "right",
        axisLabel: {
          formatter: "{value} 元",
        },
      },
    ],
    series: [
      {
        name: "订单数量",
        type: "bar",
        data: data.orderCount,
        yAxisIndex: 0,
        itemStyle: {
          color: "#5e35b1",
        },
      },
      {
        name: "订单金额",
        type: "line",
        yAxisIndex: 1,
        data: data.orderAmount,
        smooth: true,
        lineStyle: {
          color: "#ed6c02",
          width: 3,
        },
        symbol: "circle",
        symbolSize: 8,
      },
    ],
  };

  orderStatsChartInstance.setOption(option);
};

// 渲染商家分类图表
const renderMerchantCategoryChart = (
  data: { value: number; name: string }[]
) => {
  if (!merchantCategoryChart.value) return;

  if (!merchantCategoryChartInstance) {
    merchantCategoryChartInstance = echarts.init(merchantCategoryChart.value);
  }

  const option = {
    title: {
      text: "商家订单分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)",
    },
    legend: {
      orient: "horizontal",
      bottom: "10",
    },
    series: [
      {
        name: "商家订单",
        type: "pie",
        radius: "60%",
        center: ["50%", "50%"],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          formatter: "{b}: {d}%",
        },
      },
    ],
  };

  merchantCategoryChartInstance.setOption(option);
};

// 渲染商品分类图表
const renderProductCategoryChart = (
  data: { value: number; name: string }[]
) => {
  if (!productCategoryChart.value) return;

  if (!productCategoryChartInstance) {
    productCategoryChartInstance = echarts.init(productCategoryChart.value);
  }

  const option = {
    title: {
      text: "商品销量分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)",
    },
    legend: {
      orient: "horizontal",
      bottom: "10",
    },
    series: [
      {
        name: "商品销量",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "18",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: data,
      },
    ],
  };

  productCategoryChartInstance.setOption(option);
};

// 渲染骑手统计图表
const renderRiderStatsChart = (data: {
  dates: string[];
  riderCount: number[];
  deliveryCount: number[];
}) => {
  if (!riderStatsChart.value) return;

  if (!riderStatsChartInstance) {
    riderStatsChartInstance = echarts.init(riderStatsChart.value);
  }

  const option = {
    title: {
      text: "骑手配送统计",
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["骑手数量", "配送数量"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "骑手数量",
        type: "line",
        data: data.riderCount,
        smooth: true,
        lineStyle: {
          color: "#1976d2",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(25, 118, 210, 0.5)",
              },
              {
                offset: 1,
                color: "rgba(25, 118, 210, 0.1)",
              },
            ],
          },
        },
      },
      {
        name: "配送数量",
        type: "line",
        data: data.deliveryCount,
        smooth: true,
        lineStyle: {
          color: "#2e7d32",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(46, 125, 50, 0.5)",
              },
              {
                offset: 1,
                color: "rgba(46, 125, 50, 0.1)",
              },
            ],
          },
        },
      },
    ],
  };

  riderStatsChartInstance.setOption(option);
};

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  userGrowthChartInstance?.resize();
  orderStatsChartInstance?.resize();
  merchantCategoryChartInstance?.resize();
  productCategoryChartInstance?.resize();
  riderStatsChartInstance?.resize();
};

onMounted(() => {
  // 设置默认时间范围
  handleTimeRangeChange(timeRange.value);

  // 监听窗口大小变化
  window.addEventListener("resize", handleResize);

  // 组件卸载时移除监听
  return () => {
    window.removeEventListener("resize", handleResize);
    userGrowthChartInstance?.dispose();
    orderStatsChartInstance?.dispose();
    merchantCategoryChartInstance?.dispose();
    productCategoryChartInstance?.dispose();
    riderStatsChartInstance?.dispose();
  };
});
</script>

<style scoped>
.statistics-view {
  width: 100%;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-container {
  margin-top: 20px;
}

.network-error-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
